<template>
  <div class="countDownBox">
    <div class="sqBox">{{ day }}</div>
    <span class="unit">天</span>
    <div class="sqBox">{{ hour }}</div>
    <span class="unit">:</span>
    <div class="sqBox">{{ minute}}</div>
    <span class="unit">:</span>
    <div class="sqBox">{{ second }}</div>
  </div>
</template>

<script setup>

const nuxtApp=useNuxtApp()

const props=defineProps({
  time:{
    type:[String,Number],
    default:''
  }
})


const emit=defineEmits(['timeStart','timeEnd'])

//更新动态数据，需要ref(any)
const day=ref(0)
const hour=ref(0)
const minute=ref(0)
const second=ref(0)
const timer=ref(null)
const countDownTime=ref(0)

//先关闭倒计时
// if(process.client){
//   const data= timeTrans()
// }


function timeTrans(){
  //事件定时器
  
  
  // let end=new Date(props.time).getTime()
  let now=new Date().getTime()
  let timeFinish=0
  // console.log("props.time: ",props.time)
  if(typeof props.time ==='string'){
    timeFinish=new Date(props.time).getTime()
  }
  // console.log("timeFinish: ",timeFinish)
  countDownTime.value=(timeFinish-now)  / 1000 //除以1000 为毫秒

  // console.log("now: ",now)
  // console.log("countDownTime.value: ",countDownTime.value)
  closeTimer()
  
  timer.value=setInterval(()=>{
    countDownTime.value--
    //利用计算属性更新赋值
    // console.log("ountDownTime: ",countDownTime)
    let cd = computed(()=> nuxtApp.$formatSecondToDate(countDownTime.value) )
    // console.log("cd: ",cd)
    day.value= cd.value.day
    hour.value=cd.value.hour
    minute.value=cd.value.minute
    second.value= cd.value.second
    // console.log("second: ",second)
    if(countDownTime.value<=0){
      console.log('倒计时已结束')
      closeTimer()
      emit('timeEnd')
    }
    return cd 
    
    
  },1000)


  
}

function closeTimer(){
  if(timer.value) clearInterval(timer.value)

}

onMounted(()=>{
  timeTrans()
})

onUnmounted(()=>{
  closeTimer()
})
</script>

<style lang="scss" scoped>
@import '@/assets/css/common.scss';
@import '@/assets/css/index.scss';
.countDownBox{
  display: flex;
  align-items: center;

  .sqBox{
    padding: 1px 2px;
    background-color: $lightRed;
    font-size: 14px;
    margin: 0 3px;
    border-radius: 5px;
    color: #fff;
  }
  .unit{
    font-size: 14px;
    color: #aaa;
  }
}
</style>